package cc.wanforme.st.server.util;

import java.util.Collection;
import java.util.Objects;
import java.util.function.Function;

import org.springframework.util.StringUtils;

import cc.wanforme.st.server.exception.MunkRuntimeException;

/** 断言检查器
 * @author wanne
 * @since 2021-09-29
 */
@Deprecated
public class MunkAssert {
	
	
	/** 检查对象是否通过检查，失败则抛出异常
	 * @param <T>
	 * @param t 检查对象
	 * @param checker 检查函数，入参 T，返回bool，是否通过检查
	 * @param failMsg 检查失败时抛出异常的字符串信息
	 */
	public static <T> void check(T t, Function<T, Boolean> checker, RuntimeException e) {
		if(!checker.apply(t)) {
			throw e;
		}
	}
	
	/** 检查对象是否通过检查，失败则抛出异常
	 * @param <T>
	 * @param t 检查对象
	 * @param checker 检查函数，入参 T，返回bool，是否通过检查
	 * @param failMsg 检查失败时抛出异常的字符串信息
	 * @see #check(Object, Function, RuntimeException)
	 */
	public static <T> void check(T t, Function<T, Boolean> checker, String failMsg) {
		check(t, checker, new MunkRuntimeException(failMsg));
	}
	
	
	/** 检查所有对象
	 * @param <T>
	 * @param checker
	 * @param e
	 * @param args
	 * @see #check(Object, Function, RuntimeException)
	 */
	public static void checkAll(Function<Object, Boolean> checker, RuntimeException e, Object... args) {
		for (Object t : args) {
			check(t, checker, e);
		}
	}
	
	/** null 检查
	 * @param obj
	 * @param nullMsg
	 */
	public static void nonNull(Object obj, String nullMsg) {
		check(obj, Objects::nonNull, nullMsg);
	}
	
	/** 字符串 empty 检查
	 * @param obj
	 * @param nullMsg
	 */
	public static void notEmpty(String str, String emptyMsg) {
		check(str, StringUtils::hasText, emptyMsg);
	}
	
	/** 集合空检查
	 * @param obj
	 * @param nullMsg
	 */
	public static <T> void notEmptyCollection(Collection<T> collection, String emptyMsg) {
		notEmptyCollection(collection, new MunkRuntimeException(emptyMsg));
	}
	public static <T> void notEmptyCollection(Collection<T> collection, RuntimeException e) {
		if(collection == null || collection.isEmpty()) {
			throw e;
		}
	}
	
	/** 检查集合中的每一个元素
	 * @param obj
	 * @param nullMsg
	 */
	public static <T> void checkElements(Collection<T> collection, Function<T, Boolean> checker, RuntimeException e) {
		for (T t : collection) {
			if(!checker.apply(t)) {
				throw e;
			}
		}
	}
	public static <T> void checkElements(Collection<T> collection, Function<T, Boolean> checker, String emptyMsg) {
		int index = 0;
		for (T t : collection) {
			if(!checker.apply(t)) {
				throw new MunkRuntimeException(emptyMsg + " > index:" + index);
			}
			index++;
		}
	}
	
}
